package com.ssii.www.myproject.web.controller;

import com.ssii.www.myproject.common.util.AjaxResult;
import com.ssii.www.myproject.common.util.LogUtils;
import com.ssii.www.myproject.common.util.PageList;
import com.ssii.www.myproject.domain.Permission;
import com.ssii.www.myproject.query.PermissionQuery;
import com.ssii.www.myproject.service.PermissionService;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/permission")
public class PermissionController {
  @Autowired
  private PermissionService permissionService;

  @RequiresPermissions("permission:index")
  @RequestMapping("/index")
  public String index() {
    return "permission/index";
  }

  @RequestMapping("/save")
  @ResponseBody
  public AjaxResult save(Permission permission) {
    permission.setState(1L);
    permissionService.save(permission);
    return new AjaxResult();
  }

  @ResponseBody
  @RequestMapping("/page")
  public Map<String,Object> page(PermissionQuery query) {

    Map<String, Object> map = new HashMap<>();
    //点击角色返回对应角色的权限
    if (query.getRole_id() != null) {
      PageList<Permission> permissions = permissionService.getPagePermissionsByRoleId(query);
      map.put("rows",permissions.getRows());
      map.put("page",permissions.getPage());
      map.put("total",permissions.getTotal());
      return map;
    }
    Page<Permission> pageByQuery = permissionService.findPageByQuery(query);
    map.put("rows", pageByQuery.getContent());
    map.put("page", pageByQuery.getTotalPages());
    map.put("total", pageByQuery.getTotalElements());
    return map;

  }

  @ResponseBody
  @RequestMapping("/delete")
  public AjaxResult delete(@RequestParam(value = "id") Long ud) {
    permissionService.delete(ud);
    return new AjaxResult();
  }

  @ResponseBody
  @RequestMapping("/change")
  public AjaxResult change(Permission permission) {
//    this.permission = permission;
    Long state = permission.getState();
    Long change = permissionService.change(state);
    permission.setState(change);
    permissionService.save(permission);
    return new AjaxResult();
  }
}
